﻿#include "AF_Timer.h"
#include "AF_Platform.h"

namespace AF
{
	Link<Timer*> Timer::TimerLink;
	Link<Timer*> Timer::TimerExactLink;
	unsigned int Timer::NameID = 0;


	void Timer::AddTimer(Timer* pTimer)
	{
		TimerLink.Add(pTimer);
	}

	void Timer::RemoveTimer(Timer* pTimer)
	{
		if(TimerLink.Remove(pTimer) == false)
			TimerExactLink.Remove(pTimer);
	}

	void Timer::UpdateTimers()
	{
		FOREACH(Timer*, _ppTimer, TimerLink)
		{
			(*_ppTimer)->Update();
		}
	}

	void Timer::UpdateExactTimers()
	{
		FOREACH(Timer*, _ppTimer, TimerExactLink)
		{
			(*_ppTimer)->Update();
		}
	}



	Timer::Timer() :
		m_strName("Timer_"),
		m_ttSave(0),
		m_isRun(false)
	{
		char szID[5];
		_SPRINTF(szID, "%d", NameID++);
		m_strName.append(szID);
		AddTimer(this);
	}

	Timer::Timer(_STRING strName) :
		m_strName(strName),
		m_ttSave(0),
		m_isRun(false)
	{
		AddTimer(this);
	}

	Timer::~Timer()
	{
		RemoveTimer(this);
	}

	void Timer::Exact()
	{
		TimerLink.Remove(this);
		TimerExactLink.Add(this);
	}

	bool Timer::Start(TimeTicks ttInterval)
	{
		if(ttInterval > 0)
			SetInterval(ttInterval);

		m_isRun = true;
		m_ttSave = AF_pTHEPLATFORM->GetTimeTicks();
		return true;
	}

	void Timer::Stop()
	{
		m_isRun = false;
	}

	void Timer::Update()
	{
		static TimeTicks ttTime;

		if(m_isRun)
		{
			ttTime = AF_pTHEPLATFORM->GetTimeTicks();
			if(ttTime - m_ttSave >= ATTRIB(Interval))
			{
				// 如果不继续，停止计时
// 				if(OnRunTimer() == false && m_isRun)
// 					Stop();

				OnRunTimer();
				
				if(m_isRun)
					m_ttSave = ttTime;
			}
		}
	}

	void Timer::OnRunTimer()
	{
		if(GetRunClass() != NULL)
			GetRunClass()->OnRun(this);
	}

	bool Timer::IsRun()
	{
		return m_isRun;
	}

}